<template>
    <div>
        <div style="margin-top: 20px; width: 100%">
            <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                <div class="query-row">
                    <el-form-item label="出库单编号">
                        <el-input v-model="page.outboundOrderCode" />
                    </el-form-item>
                    <el-form-item label="销售订单编号" style="margin-left: -20px">
                        <el-input v-model="page.salesOrderNumber" />
                    </el-form-item>
                    <el-form-item label="客户名称" style="margin-left: 20px">
                        <el-input v-model="page.customerName" />
                    </el-form-item>
                </div>
                <div class="query-row">
                    <el-form-item label="出库日期" style="margin-left: 20px">
                        <el-date-picker v-model="page.outboundDate" type="datetime"
                            value-format="YYYY-MM-DD HH:mm:ss" />
                    </el-form-item>
                    <el-form-item label="单据状态" style="margin-left: 20px">
                        <el-select v-model="page.documentStatus" placeholder="请选择单据状态" size="large" filterable>
                            <el-option label="草稿" :value="1" checked />
                            <el-option label="已确认" :value="2" />
                            <el-option label="审批中" :value="3" />
                            <el-option label="已审批" :value="4" />
                            <el-option label="已完成" :value="5" />
                        </el-select>
                    </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" @click="fetchData">查询</el-button>
                    <el-button type="primary" @click="empty">清空</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-button type="primary" @click="AddInfo()">新增</el-button>
        <el-button type="primary" @click="Derive()">导出</el-button>
        <el-button type="primary" @click="kanban()">看板</el-button>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="outboundOrderCode" label="出库单编号" />
            <el-table-column prop="outboundOrderName" label="出库单名称" />
            <el-table-column prop="salesOrderNumber" label="销售订单编号" />
            <el-table-column prop="customerCode" label="客户编号" />
            <el-table-column prop="customerName" label="客户名称" />
            <el-table-column prop="outboundDate" label="出库日期" />
            <el-table-column prop="documentStatus" label="单据状态">
                <template #default="scope">
                    <span v-if="scope.row.documentStatus === 1">草稿</span>
                    <span v-else-if="scope.row.documentStatus === 2">已确认</span>
                    <span v-else-if="scope.row.documentStatus === 3">审批中</span>
                    <span v-else-if="scope.row.documentStatus === 4">已审批</span>
                    <span v-else-if="scope.row.documentStatus === 5">已完成</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
                <template #default="scope">
                    <el-button size="small" @click="editItem(scope.row)">编辑</el-button>
                    <el-button size="small" @click="DelFrom(scope.row.salesReceiptId)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div>
            <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
                :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>

    <div>
        <el-dialog v-model="dialogFormVisible" title="添加销售出库单" width="1000">
            <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <div style="display: flex; flex-wrap: wrap;">
                    <!-- 第一排，两条数据 -->
                    <el-form-item label="出库单编号" prop="outboundOrderCode" style="flex: 0 0 50%; max-width: 50%;">
                        <el-input v-model="ruleForm.outboundOrderCode" autocomplete="off"
                            style="width: 180px; height: 30px" :readonly="ruleForm.autoGenerate" clearable
                            @click.native="handleCodeClick" />
                        <template slot="prepend">R</template>
                        <el-switch width="40" v-model="ruleForm.autoGenerate" active-text="自动生成" active-color="#67C23A"
                            @change="handleSwitchChange" />
                    </el-form-item>
                    <el-form-item label="出库单名称" prop="outboundOrderName" style="flex: 0 0 50%; max-width: 50%;">
                        <el-input v-model="ruleForm.outboundOrderName" />
                    </el-form-item>
                    <!-- 第二排，三条数据 -->
                    <el-form-item label="销售订单编号" prop="salesOrderNumber" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.salesOrderNumber" />
                    </el-form-item>
                    <el-form-item label="客户编码" prop="customerCode" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.customerCode" />
                        <el-button type="primary" @click="redsinfo()">客户管理</el-button>
                    </el-form-item>
                    <el-form-item label="客户名称" prop="customerName" style="flex: 0 0 33.33%; max-width: 33.33%;">
                        <el-input v-model="ruleForm.customerName" />
                    </el-form-item>
                    <!-- 备注单独一排 -->
                    <el-form-item label="备注" prop="remarks" style="width: 100%;">
                        <el-input v-model="ruleForm.remarks" type="textarea" />
                    </el-form-item>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="AddForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
    <div>
        <el-dialog v-model="dialogFormVisible2" title="显示客户信息" width="1000">
            <div style="margin-top: 20px; width: 100%">
                <el-form :inline="true" :model="ruleForm" style="font-size: 15px; width: 100%" class="query-form">
                    <el-form-item label="客户编码" style="margin-left: 20px">
                        <el-input v-model="page1.customerNo" />
                    </el-form-item>
                    <el-form-item label="客户名称" style="margin-left: 20px">
                        <el-input v-model="page1.customerName" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="ShowProduct">查询</el-button>
                        <el-button type="primary" @click="empty1">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table :data="tableData1" border style="width: 100%">
                <el-table-column label="选择" width="30">
                    <template #default="scope">
                        <el-radio v-model="selectedRow" :label="scope.row"></el-radio>
                    </template>
                </el-table-column>
                <el-table-column prop="customerNo" label="客户编码" />
                <el-table-column prop="customerName" label="客户名称" />
                <el-table-column prop="customerEng" label="客户简介" />
                <el-table-column prop="customerTypeName" label="客户类型" />
                <el-table-column prop="customerAddress" label="客户电话" />
                <el-table-column prop="customeroffadd" label="联系人" />
                <el-table-column prop="customeremadd" label="联系人-电话" />
            </el-table>
            <div>
                <el-pagination v-model:current-page="page1.PageIndex" v-model:page-size="page1.PageSize"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="page1.totalCount" @size-change="handleSizeChange1" @current-change="handleCurrentChange1" />
            </div>
            <el-button type="primary" @click="AddProudctInfo()">确定</el-button>
            <el-button type="primary" @click="dialogFormVisible2 = false">取消</el-button>
        </el-dialog>

    </div>



    <div>
        <el-dialog v-model="dialogFormVisible1" title="修改销售出库单" width="1000">
            <div>
                <el-form ref="ruleFormRef" style="max-width: 900px" :model="ruleForm" label-width="auto"
                    class="demo-ruleForm" :size="formSize" status-icon>
                    <div style="display: flex; flex-wrap: wrap;">
                        <!-- 第一排，两条数据 -->
                        <el-form-item label="出库单编号" prop="outboundOrderCode" style="flex: 0 0 50%; max-width: 50%;">
                            <el-input v-model="ruleForm.outboundOrderCode" autocomplete="off"
                                style="width: 180px; height: 30px" :readonly="ruleForm.autoGenerate" clearable
                                @click.native="handleCodeClick" />
                            <template slot="prepend">R</template>
                            <el-switch width="40" v-model="ruleForm.autoGenerate" active-text="自动生成"
                                active-color="#67C23A" @change="handleSwitchChange" />
                        </el-form-item>
                        <el-form-item label="出库单名称" prop="outboundOrderName" style="flex: 0 0 50%; max-width: 50%;">
                            <el-input v-model="ruleForm.outboundOrderName" />
                        </el-form-item>
                        <!-- 第二排，三条数据 -->
                        <el-form-item label="销售订单编号" prop="salesOrderNumber"
                            style="flex: 0 0 33.33%; max-width: 33.33%;">
                            <el-input v-model="ruleForm.salesOrderNumber" />
                        </el-form-item>
                        <el-form-item label="客户编码" prop="customerCode" style="flex: 0 0 33.33%; max-width: 33.33%;">
                            <el-input v-model="ruleForm.customerCode" />
                        </el-form-item>
                        <el-form-item label="客户名称" prop="customerName" style="flex: 0 0 33.33%; max-width: 33.33%;">
                            <el-input v-model="ruleForm.customerName" />
                        </el-form-item>
                        <!-- 备注单独一排 -->
                        <el-form-item label="备注" prop="remarks" style="width: 100%;">
                            <el-input v-model="ruleForm.remarks" type="textarea" />
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <br />
            <div>
                <el-table :data="tableData1" border style="width: 100%">
                    <el-table-column type="selection" :selectable="selectable" width="55" />
                    <el-table-column prop="materialnumber" label="产品编码" />
                    <el-table-column prop="materialname" label="产品名称" />
                    <el-table-column prop="specification" label="规格型号" />
                    <el-table-column prop="unit" label="单位" />
                    <el-table-column prop="inboundNumber" label="出库数量" />
                    <el-table-column prop="lotnumber" label="批次号" />
                    <el-table-column prop="whethertest" label="是否检验">
                        <template #default="scope">
                            <span v-if="scope.row.documentStatus === 1">是</span>
                            <span v-else>否</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" />
                </el-table>
            </div>
            <div>
                <el-pagination v-model:current-page="pageinfo.PageIndex" v-model:page-size="pageinfo.PageSize"
                    :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pageinfo.totalCount" @size-change="handleSizeChange2"
                    @current-change="handleCurrentChange2" />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="UpdateForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>


</template>
<script lang="ts" setup>
import axios from 'axios';
import { ElMessage, ElMessageBox, ElTable, ElTableColumn, ElPagination } from 'element-plus';
import { onMounted, ref, reactive, computed } from 'vue';
const apiUrl = import.meta.env.VITE_APP_API_URL;
const tableData = ref([]);
const tableData1 = ref([]);
const dialogFormVisible = ref(false)
const dialogFormVisible1 = ref(false)
const dialogFormVisible2 = ref(false)

const kanban = () => {
    window.location.href = 'http://localhost:8075/webroot/decision/view/duchamp?viewlet=%25E5%2587%25BA%25E5%25BA%2593%25E7%25BB%259F%25E8%25AE%25A1%25E6%258A%25A5%25E8%25A1%25A8.fvs&page_number=1';
}


const pageinfo = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    totalPage: 0,
})

const redsinfo = () => {
    dialogFormVisible2.value = true;
    ShowProduct();
}

const selectedRow = ref(); // 用于存储选中的行
const AddProudctInfo = () => {
    if (selectedRow.value) {
        // 将选中的单条数据存入 sessionStorage
        sessionStorage.setItem('Customer', JSON.stringify(selectedRow.value));
        console.log('选中的数据已存入 sessionStorage', sessionStorage.getItem('Customer'));
    } else {
        ElMessage.warning('请选择一条生产任务数据');
    }
    dialogFormVisible2.value = false;
    // 从 sessionStorage 中获取选中的生产任务数据
    const selectedTaskData = sessionStorage.getItem('Customer');
    if (selectedTaskData) {
        const task = JSON.parse(selectedTaskData);
        console.log('解析后的生产任务数据', task);
        if (task.customerNo) {
            // 将 taskName 反填到生产任务字段
            ruleForm.customerCode = task.customerNo;
            ruleForm.customerName = task.customerName;
            console.log('生产任务字段已反填:', ruleForm.customerCode);
        } else {
            console.log('生产任务数据中不包含 taskName 字段');
        }
    } else {
        console.log('sessionStorage 中没有选中的生产任务数据');
    }
}


// 查询表单数据
const page1 = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    totalPage: 0,
    customerNo: '',
    customerName: '',
});

// 整合显示生产任务、查询和分页的方法
const ShowProduct = () => {
    axios.get(apiUrl +'/T5/Customer/GetCustomer', { params: page1 })
        .then((res) => {
            tableData1.value = res.data.data;
            page1.totalCount = res.data.totalCount;
            page1.totalPage = res.data.totalPage;
        })
};

const handleSizeChange1 = (val: number) => {
    console.log(`${val} items per page`);
    page1.PageSize = val;
    ShowProduct();
};
const handleCurrentChange1 = (val: number) => {
    console.log(`current page: ${val}`);
    page1.PageIndex = val;
    ShowProduct();
};

const empty1 = () => {
    page1.customerNo = '';
    page1.customerName = '';
    ShowProduct();
};


const selectable = (row: User) => ![1, 2].includes(row.id)


//显示物料信息
const showInfo = () => {
    axios.get(apiUrl +'/T5/ProductInfo/GetMaterialmanagement', { params: pageinfo })
        .then(res => {
        tableData1.value = res.data.data;
        pageinfo.totalCount = res.data.totalCount;
        pageinfo.totalPage = res.data.totalPage;
    })
}
const handleSizeChange2 = (val: number) => {
    console.log(`${val} items per page`);
    pageinfo.PageSize = val;
    showInfo();
};
const handleCurrentChange2 = (val: number) => {
    console.log(`current page: ${val}`);
    pageinfo.PageIndex = val;
    showInfo();
};


// 查询表单数据
const page = reactive({
    PageIndex: 1,
    PageSize: 10,
    totalCount: 0,
    totalPage: 0,
    outboundOrderCode: '',
    salesOrderNumber: '',
    customerName: '',
    outboundDate: '',
    documentStatus: '',
});

// 整合显示生产任务、查询和分页的方法
const fetchData = () => {
    const params = { ...page };
    if (!params.outboundDate) {
        delete params.outboundDate;
    }
    axios.get(apiUrl +'/T5/ProductInfo/GetSaleReceipt', { params })
        .then((res) => {
            tableData.value = res.data.data;
            page.totalCount = res.data.totalCount;
            page.totalPage = res.data.totalPage;
        })
};
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    page.PageSize = val;
    fetchData();
};
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    page.PageIndex = val;
    fetchData();
};
const empty = () => {
    page.outboundOrderCode = '';
    page.salesOrderNumber = '';
    page.customerName = '';
    page.outboundDate = '';
    page.documentStatus = '';
    fetchData();
};

//逻辑销售出库单
const DelFrom = (salesReceiptId: any) => {
    axios.put(apiUrl +'/T6/ProductInfos/DelSalesReceipt', { salesReceiptId: salesReceiptId })
        .then((res) => {
            if (res.data.code == 204) {
                ElMessage({
                    message: res.data.msg,
                    type: 'success',
                })
                fetchData();
            } else {
                ElMessage({
                    message: '删除失败',
                    type: 'error',
                })
            }
        })
}

//导出销售出库单
const Derive = () => {
    window.location.href = apiUrl+'/T5/ProductInfo/ExeclSalesReceipt'
}


const AddInfo = () => {
    dialogFormVisible.value = true;
    // 初始化 ruleForm
    ruleForm.salesReceiptId = 0;
    ruleForm.outboundOrderCode = '';
    ruleForm.outboundOrderName = '';
    ruleForm.salesOrderNumber = '';
    ruleForm.customerCode = '';
    ruleForm.outboundDate = new Date();
    ruleForm.documentStatus = 1;
    ruleForm.remarks = '';
    ruleForm.customerName = '';
    ruleForm.isDelete = false;
};

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    salesReceiptId: 0,
    outboundOrderCode: '',
    outboundOrderName: '',
    salesOrderNumber: '',
    customerCode: '',
    outboundDate: new Date(),
    documentStatus: 1,
    remarks: '',
    customerName: '',
    isDelete: false,
    autoGenerate: false, // 是否自动生成
})

const editItem = (item) => {
    dialogFormVisible1.value = true;
    // 创建数据副本
    const itemCopy = { ...item };
    // 将副本数据复制到 ruleForm
    Object.assign(ruleForm, itemCopy);

    showInfo();
};

const UpdateForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 修改为使用 axios.put 方法
            axios.put(apiUrl +'/T6/ProductInfos/UpdateSalesReceipt', ruleForm)
                .then(res => {
                    if (res.data.code === 206) {
                        ElMessage.success("修改成功!");
                        dialogFormVisible1.value = false;
                        fetchData();
                    } else {
                        ElMessage.error(`修改失败: ${res.data.message || '未知错误'}`);
                    }
                })
                .catch((error) => {
                    console.error('修改物料产品失败:', error);
                    ElMessage.error('修改物料产品失败，请稍后重试');
                });
        } else {

            console.log('error submit!', fields);
            ElMessage.error('表单验证失败，请检查输入内容');
        }
    });
};

// 生成销售出库编号（GYLX+时间戳）
const generateCode = () => {
    const timestamp = new Date().toISOString().replace(/[-:TZ]/g, "").substring(0, 14); // 获取精确到毫秒的时间戳
    ruleForm.outboundOrderCode = `XSCK${timestamp}`;
};

const handleSwitchChange = (val: boolean) => {
    ruleForm.autoGenerate = val;
    if (val) {
        generateCode(); // 开启自动生成时立即生成
    } else {
        ruleForm.outboundOrderCode = ""; // 关闭时清空编号
    }
};

const handleCodeClick = () => {
    if (ruleForm.autoGenerate) {
        generateCode(); // 点击输入框时重新生成
    }
};

const AddForm = async (formEl: FormInstance | undefined) => {

    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log(ruleForm);
            axios.post(apiUrl +'/T6/ProductInfos/AddSalesReceipt', ruleForm)
                .then(res => {
                    if (res.data.code == 100) {
                        ElMessage.success(res.data.msg);
                        dialogFormVisible.value = false;
                        fetchData();
                    } else {
                        ElMessage.error("添加失败!");
                    }
                });
        } else {
            console.log('error submit!', fields);
        }
    });
};

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}));


onMounted(() => {
    fetchData();
});
</script>
<style></style>